﻿using System;
using System.Drawing;
using System.Windows.Forms;
using Jage.Logic.Resources;

namespace Jage.GameEditor.Controls.Sprites
{
    public partial class SpritesheetSpritePreview : UserControl
    {
        public SpritesheetSpritePreview()
        {
            InitializeComponent();
        }

        public void SetResource(Data.Sprite sprite)
        {
            Spritesheet = ResourceIO.GetBitmap(sprite.Spritesheet.Resource);
            Sprite = sprite;
        }


        private void PanelPreviewSpritePaint(object sender, PaintEventArgs e)
        {
            if (Spritesheet == null && Sprite == null) return;
            var spriteWidth = Sprite.Width;
            var width = Math.Min(Width, spriteWidth);
            var spriteHeight = Sprite.Height;
            var zoom = (float) width/spriteWidth;
            e.Graphics.DrawImage(Spritesheet, new Rectangle(0,0, width, (int)(zoom * spriteHeight)), Sprite.X, Sprite.Y, Sprite.Width, Sprite.Height, GraphicsUnit.Pixel);
            DrawOriginMark(e.Graphics, new Point((int)(zoom * Sprite.OriginX), (int)(zoom * Sprite.OriginY)));
        }

        private void DrawOriginMark(Graphics graphics, Point origin)
        {
            graphics.DrawLine(Pens.Cyan, origin.X, origin.Y - 2, origin.X, origin.Y + 2);
            graphics.DrawLine(Pens.Cyan, origin.X - 2, origin.Y, origin.X + 2, origin.Y);
        }

        private Bitmap Spritesheet { get; set; }

        private Data.Sprite _sprite;
        public Data.Sprite Sprite
        {
            get { return _sprite; }
            set 
            { 
                _sprite = value;
                Visible = _sprite != null;
                Refresh();
            }
        }

    }
}
